package com.qws.xprinter.flutter_xprinter.queue

import android.util.Log
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.ReentrantLock

class PrintTaskQueue {
    private val taskQueue: BlockingQueue<Runnable> = LinkedBlockingQueue()
    private val pauseLock = ReentrantLock()
    private val unpaused: Condition = pauseLock.newCondition()
    private var listener: PrintQueueListener? = null

    @Volatile
    private var isPaused = true
    private var workerThread: Thread


    init {
        workerThread = Thread { this.runWorker() }
        workerThread.start()
    }

    fun setPrintQueueListener(queueListener: PrintQueueListener) {
        listener = queueListener
    }

    private fun runWorker() {
        while (!Thread.currentThread().isInterrupted) {
            pauseLock.lock()
            try {
                // 检查是否暂停或队列为空，进入等待
                while (isPaused || taskQueue.isEmpty()) {
                    if (Thread.currentThread().isInterrupted) {
                        return
                    }
                    if (isPaused) {
                        unpaused.await()
                    }
                    if (taskQueue.isEmpty()) {
                        // 恢复队列为空时的回调
                        listener?.onQueueEmpty()
                        Log.d("PrintTaskQueue", "onQueueEmpty")
                        unpaused.await()
                    }
                }
            } catch (e: InterruptedException) {
                Thread.currentThread().interrupt()
                return
            } finally {
                pauseLock.unlock()
            }
            // 取出并执行任务
            val task = taskQueue.poll()
            if (task != null) {
                try {
                    task.run()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    fun addTask(task: Runnable) {
        taskQueue.offer(task)
    }

    fun pause() {
        pauseLock.lock()
        try {
            isPaused = true
        } finally {
            pauseLock.unlock()
        }
    }

    fun resume() {
        pauseLock.lock()
        try {
            isPaused = false
            unpaused.signalAll()
        } finally {
            pauseLock.unlock()
        }
    }

    fun shutdown() {
        workerThread.interrupt()
    }

    interface PrintQueueListener {
        fun onQueueEmpty()
    }
}